package com.financing.wap.web.controller.api;

import java.util.Collections;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.financing.wap.common.CommonConstantUtil;
import com.financing.wap.common.CommonConstantUtil.CommonStatus;
import com.financing.wap.common.Pager;
import com.financing.wap.common.ResultMap;
import com.financing.wap.dto.DstArticleDTO;
import com.financing.wap.dto.DstUserArticleDTO;
import com.financing.wap.dto.DstUserInfoDTO;
import com.financing.wap.service.IDstArticleService;
import com.financing.wap.service.IDstUserArticleService;
import com.financing.wap.service.IDstUserInfoService;
import com.financing.wap.service.weixin.service.WeixinService;
import com.financing.wap.util.DTOdateSetUtil;
import com.financing.wap.util.DateUtil;
import com.financing.wap.util.StringUtil;
import com.financing.wap.vo.DstUserInfoVO;
import com.financing.wap.web.controller.BaseController;

@Controller("dstUserArticleController")
@RequestMapping("/api/dstUserArticle")
public class DstUserArticleController extends BaseController  { 

	private Logger logger = Logger.getLogger(getClass());
	@Autowired
	private IDstUserInfoService dstUserInfoService;
	
	@Autowired
	private IDstUserArticleService dstUserArticleService;

	@Autowired
	private IDstArticleService dstArticleService;
	
	@Autowired
	private WeixinService weixinJincsServiceImpl;
	
	@RequestMapping("/listDstUserArticle")
	@ResponseBody
	public ResultMap list(HttpServletRequest request, DstUserArticleDTO dstUserArticle,Pager pager){
		ResultMap result = new ResultMap();
		
		try{
			logger.info("query dstUserArticle list begin .......");
			
			dstUserArticle.setBegin(pager.getStartIndex());
			dstUserArticle.setPageSize(pager.getPageSize());
			
			int count = dstUserArticleService.queryListCount(dstUserArticle);
			
			pager.setTotalCount(count);
			
			List<DstUserArticleDTO> dstUserArticleList = null;
			
			if(count > 0){
				dstUserArticleList = dstUserArticleService.queryList(dstUserArticle);
			}else{
				dstUserArticleList = Collections.emptyList();
			}
			result.setAttribute("pager", pager);
			result.setAttribute("list", dstUserArticleList);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			
			logger.info("query dstUserArticle list end .......");
		}catch(Exception e){
			log.error("query dstUserArticle error!",e);
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		
		return result;
	}
	
	@RequestMapping("/addDstUserArticle")
	@ResponseBody
	public ResultMap add(HttpServletRequest request, DstUserArticleDTO dstUserArticle){
		ResultMap result = new ResultMap();
		
		try{
			logger.info("add dstUserArticle  begin .......");
			
			DTOdateSetUtil.setCreateInfo(dstUserArticle);
			DTOdateSetUtil.setUpdateInfo(dstUserArticle);
			
			int id = dstUserArticleService.insert(dstUserArticle);
			result.setAttribute("id", id);
			
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			
			logger.info("add dstUserArticle list end .......");
		}catch(Exception e){
			log.error("add dstUserArticle error!",e);
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		
		return result;
	}
	
	/***
	 * 用户访问文章接口
	 * @param request
	 * @return
	 */
	@RequestMapping("/detailDstUserArticle")
	@ResponseBody
	public ResultMap detail(HttpServletRequest request){
		ResultMap result = new ResultMap();
		try{
			logger.info("query detail dstUserArticle  begin .......");
			//当前登录用户的openid
			String openid=request.getParameter("openid");
			//文章所属用户openid
			String userOpenid=request.getParameter("userOpenid");
			String dstArticleCode=request.getParameter("dstArticleCode");
			String create=request.getParameter("create");
			
			String articleOpenid=request.getParameter("articleOpenid");
			
			if(StringUtil.isNullOrEmptyStr(dstArticleCode)){
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}
			
			DstArticleDTO art=new DstArticleDTO();
			art.setDeleteTag(CommonStatus.DELETE_TAG_NORMAL);
			art.setDstArticleCode(dstArticleCode);
			art.setArticleStatus("1");
			DstArticleDTO article = dstArticleService.queryListGetFirst(art);
			if(article.getId()==null){
				result.setStatusCode(ResultMap.STATUS_CODE_ARTICLE_USERINFO_ERROR);
				result.setStatus(ResultMap.STATUS.SUCCESS);
				return result;
			}
			//insert一次 用户绑定文章  当前分享用户信息 
			if(!StringUtil.isNullOrEmptyStr(userOpenid)){
				DstUserArticleDTO dstUserArticle = new DstUserArticleDTO();
				dstUserArticle.setUserOpenid(userOpenid);
				dstUserArticle.setDstArticleCode(dstArticleCode);
				dstUserArticle.setDeleteTag(CommonStatus.DELETE_TAG_NORMAL);
				DstUserArticleDTO userArticle = dstUserArticleService.queryListGetFirst(dstUserArticle);
				
				if(userArticle.getId()==null&&StringUtils.isNotBlank(articleOpenid)){
					dstUserArticle.setUserOpenid(articleOpenid);
					dstUserArticle.setDstArticleCode(dstArticleCode);
					dstUserArticle.setDeleteTag(CommonStatus.DELETE_TAG_NORMAL);
					userArticle = dstUserArticleService.queryListGetFirst(dstUserArticle);
				}
				
				
				if(userArticle.getId()==null){
					if(StringUtils.isNotBlank(create)){
						try {
							dstUserArticle.setRelArticleId(article.getId());
							dstUserArticle.setDescription(article.getDescription());
							dstUserArticle.setTitle(article.getTitle());
							dstUserArticle.setThumbnail(article.getThumbnail());
							dstUserArticle.setDstArticleContent(article.getContent());
							DTOdateSetUtil.setCreateInfo(dstUserArticle);
							DTOdateSetUtil.setUpdateInfo(dstUserArticle);
							dstUserArticle.setDeleteTag(CommonStatus.DELETE_TAG_NORMAL);
							dstUserArticleService.insert(dstUserArticle);
						} catch (Exception e) {
							log.error("detailDstUserArticle dstUserArticle error!",e);
						}
					}
				}else{
					if(StringUtils.isNotBlank(userArticle.getDescription()))
						article.setDescription(userArticle.getDescription());
					if(StringUtils.isNotBlank(userArticle.getTitle()))
						article.setTitle(userArticle.getTitle());
					if(StringUtils.isNotBlank(userArticle.getThumbnail()))
						article.setThumbnail(userArticle.getThumbnail());
					article.setContent(userArticle.getDstArticleContent());
					article.setUpdateDate(userArticle.getUpdateDate());
				}
			}else{
				DstUserArticleDTO dstUserArticle = new DstUserArticleDTO();
				dstUserArticle.setDeleteTag(CommonStatus.DELETE_TAG_NORMAL);
				dstUserArticle.setUserOpenid(openid);
				dstUserArticle.setDstArticleCode(dstArticleCode);
				DstUserArticleDTO userArticle = dstUserArticleService.queryListGetFirst(dstUserArticle);
				if(userArticle.getId()==null&&StringUtils.isNotBlank(articleOpenid)){
					dstUserArticle.setUserOpenid(articleOpenid);
					dstUserArticle.setDstArticleCode(dstArticleCode);
					dstUserArticle.setDeleteTag(CommonStatus.DELETE_TAG_NORMAL);
					userArticle = dstUserArticleService.queryListGetFirst(dstUserArticle);
				}
				if(userArticle.getId()==null){
					if(StringUtils.isNotBlank(create)){
						try {
							dstUserArticle.setRelArticleId(article.getId());
							dstUserArticle.setDescription(article.getDescription());
							dstUserArticle.setTitle(article.getTitle());
							dstUserArticle.setThumbnail(article.getThumbnail());
							dstUserArticle.setDstArticleContent(article.getContent());
							DTOdateSetUtil.setCreateInfo(dstUserArticle);
							DTOdateSetUtil.setUpdateInfo(dstUserArticle);
							dstUserArticle.setDeleteTag(CommonStatus.DELETE_TAG_NORMAL);
							dstUserArticleService.insert(dstUserArticle);
						} catch (Exception e) {
							log.error("detailDstUserArticle dstUserArticle error!",e);
						}
					}
				}else{
					if(StringUtils.isNotBlank(userArticle.getDescription()))
						article.setDescription(userArticle.getDescription());
					if(StringUtils.isNotBlank(userArticle.getTitle()))
						article.setTitle(userArticle.getTitle());
					if(StringUtils.isNotBlank(userArticle.getThumbnail()))
						article.setThumbnail(userArticle.getThumbnail());
					article.setContent(userArticle.getDstArticleContent());
					article.setUpdateDate(userArticle.getUpdateDate());
				}
			}
			
			//日期格式化
			try {
				article.setRiqi(DateUtil.analysisDate(DateUtil.formatDate(article.getUpdateDate(),"yyyy-MM-dd"),true));
			} catch (Exception e) {
				log.error("detailDstUserArticle  set riqi error!",e);
			}
			
			
			DstUserInfoDTO dstUserInfo = new DstUserInfoDTO();
			dstUserInfo.setUserWechatOpenid(userOpenid);
			dstUserInfo
					.setDeleteTag(CommonStatus.DELETE_TAG_NORMAL);
			DstUserInfoDTO userinfo = dstUserInfoService
					.queryListGetFirst(dstUserInfo);

			//copy 返回信息
			DstUserInfoVO dstUserInfoVO = new DstUserInfoVO();
			BeanUtils.copyProperties(dstUserInfoVO, userinfo);
			result.setAttribute("userinfo",dstUserInfoVO);
			result.setAttribute("info",article);
			result.setAttribute("shareCode",UUID.randomUUID().toString().replace("-", ""));
			
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			
			logger.info("query detail dstUserArticle  end .......");
		}catch(Exception e){
			log.error("query detail dstUserArticle error!",e);
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		
		return result;
	}
	
	@RequestMapping("/deleteDstUserArticle")
	@ResponseBody
	public ResultMap delete(HttpServletRequest request, DstUserArticleDTO dstUserArticle){
		ResultMap result = new ResultMap();
		
		try{
			logger.info("delete dstUserArticle  begin .......");
			
			Integer id = dstUserArticle.getId();
			
			if(id==null){
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}
			
			dstUserArticleService.delete(id);
			
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			
			logger.info("delete dstUserArticle  end .......");
		}catch(Exception e){
			log.error("delete dstUserArticle error!",e);
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		
		return result;
	}
	/***
	 * 修改文章
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/updateDstUserArticle",method=RequestMethod.POST)
	@ResponseBody
	public ResultMap update(HttpServletRequest request){
		ResultMap result = new ResultMap();
		
		try{
			logger.info("update dstUserArticle  begin .......");
			//当前登录用户的openid
			String openid=request.getParameter("openid");
			String dstArticleCode=request.getParameter("dstArticleCode");
			String dstArticleContent=request.getParameter("dstArticleContent");
			String title=request.getParameter("title");
			String thumbnail=request.getParameter("thumbnail");
			String newPicMediaId=request.getParameter("newPicMediaId");
			String description=request.getParameter("description");
			if(StringUtil.isNullOrEmptyStr(openid,dstArticleCode)){
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}
			
			//查询文章是否存在
			DstArticleDTO art=new DstArticleDTO();
			art.setDeleteTag(CommonStatus.DELETE_TAG_NORMAL);
			art.setDstArticleCode(dstArticleCode);
			DstArticleDTO article = dstArticleService.queryListGetFirst(art);
			if(article.getId()==null){
				result.setStatusCode(ResultMap.STATUS_CODE_ARTICLE_USERINFO_ERROR);
				result.setStatus(ResultMap.STATUS.SUCCESS);
				return result;
			}
			
			//修改文章内容
			DstUserArticleDTO dstUserArticle=new DstUserArticleDTO();
			dstUserArticle.setDeleteTag(CommonStatus.DELETE_TAG_NORMAL);
			dstUserArticle.setUserOpenid(openid);
			dstUserArticle.setDstArticleCode(dstArticleCode);
			DstUserArticleDTO userArticle = dstUserArticleService.queryListGetFirst(dstUserArticle);
			if(userArticle.getId()==null){
				try {
					//上传picmediaId  去下载
					if(StringUtils.isNotBlank(newPicMediaId)){
						String picAddr = weixinJincsServiceImpl.getFileByMediaId("jpg", newPicMediaId);
						dstUserArticle.setPicMediaId(newPicMediaId);
						dstUserArticle.setThumbnail(CommonConstantUtil.OSS_PATH+picAddr);
					}else if(StringUtils.isNotBlank(thumbnail)){
						dstUserArticle.setThumbnail(thumbnail);
					}else{
						dstUserArticle.setThumbnail(article.getThumbnail());
					}
					//标题
					if(StringUtils.isNotBlank(title)){
						dstUserArticle.setTitle(title);
					}
					//描述
					if(StringUtils.isNotBlank(description)){
						dstUserArticle.setDescription(description);
					}
					
					dstUserArticle.setDstArticleContent(dstArticleContent);
					dstUserArticle.setRelArticleId(article.getId());
					DTOdateSetUtil.setCreateInfo(dstUserArticle);
					DTOdateSetUtil.setUpdateInfo(dstUserArticle);
					dstUserArticle.setDeleteTag(CommonStatus.DELETE_TAG_NORMAL);
					dstUserArticleService.insert(dstUserArticle);
				} catch (Exception e) {
					log.error("detailDstUserArticle dstUserArticle error!",e);
				}
			}else{
				//上传picmediaId  去下载
				if(StringUtils.isNotBlank(newPicMediaId)){
					String picAddr = weixinJincsServiceImpl.getFileByMediaId("jpg", newPicMediaId);
					userArticle.setPicMediaId(newPicMediaId);
					userArticle.setThumbnail(CommonConstantUtil.OSS_PATH+picAddr);
				}else if(StringUtils.isNotBlank(thumbnail)){
					dstUserArticle.setThumbnail(thumbnail);
				}else{
					dstUserArticle.setThumbnail(article.getThumbnail());
				}
				//标题
				if(StringUtils.isNotBlank(title)){
					userArticle.setTitle(title);
				}
				//描述
				if(StringUtils.isNotBlank(description)){
					userArticle.setDescription(description);
				}
				if(StringUtils.isNotBlank(dstArticleContent)&&!dstArticleContent.equals(userArticle.getDstArticleContent())){
					userArticle.setDstArticleContent(dstArticleContent);
				}else{
					userArticle.setDstArticleContent(null);
				}
				DTOdateSetUtil.setUpdateInfo(userArticle);
				dstUserArticleService.update(userArticle);
			}
			
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			
			logger.info("update dstUserArticle  end .......");
		}catch(Exception e){
			log.error("update dstUserArticle error!",e);
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		
		return result;
	}
}
